package com.luoxiang.socialandroid.fragment;

import static com.luoxiang.lib_common.common.Constants.MmkvConst.ACCID;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.EXTRA;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.HOSTAUDIT;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.TOKEN;
import static com.luoxiang.socialandroid.common.Constants.MmkvConst.USERID;

import android.content.Intent;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.angcyo.tablayout.DslTabLayout;
import com.angcyo.tablayout.delegate2.ViewPager2Delegate;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.luoxiang.socialandroid.R;
import com.luoxiang.socialandroid.activity.SearchActivity;
import com.luoxiang.socialandroid.activity.TestActivity;
import com.luoxiang.socialandroid.base.LazyLoadFragment;
import com.luoxiang.socialandroid.bean.GetMessageBean;
import com.luoxiang.socialandroid.bean.MineInfoBean;
import com.luoxiang.socialandroid.bean.NumberBean;
import com.luoxiang.socialandroid.bean.OurinfoBean;
import com.luoxiang.socialandroid.dialog.OneTouchChatDialog;
import com.luoxiang.socialandroid.utils.AESUtil;
import com.luoxiang.socialandroid.utils.CustomClickListener;
import com.luoxiang.socialandroid.utils.MmkvUtil;
import com.luoxiang.socialandroid.utils.NetUtils;
import com.luoxiang.socialandroid.utils.NetUtils2;
import com.lxj.xpopup.XPopup;
import com.netease.yunxin.nertc.ui.CallKitUI;
import com.netease.yunxin.nertc.ui.base.CallParam;
import com.zackratos.ultimatebarx.ultimatebarx.java.UltimateBarX;

import java.util.ArrayList;
import java.util.UUID;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * @Description 首页的fragment
 * @systemUser Administrator
 * @Author LiangXin
 * @Date 08-20-2022 周六 10:52
 */
public class HomeFragment extends LazyLoadFragment {
    private DslTabLayout tab_home;
    private ViewPager2 vp_home;
    private ImageView tosearch, imageOneTouchChat;
    private ArrayList<String> list = new ArrayList<>();
    private ArrayList<Fragment> fragmentlist = new ArrayList<>();
    private int host = -1;
    private String token;

    @Override
    protected int setContentView() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView() {
        tab_home = findViewById(R.id.tab_home);
        vp_home = findViewById(R.id.vp_home);
        tosearch = findViewById(R.id.tosearch);
        imageOneTouchChat = findViewById(R.id.imageOneTouchChat);
        UltimateBarX.addStatusBarTopPadding(findViewById(R.id.lin_home));
        token = MmkvUtil.INSTANCE.decodeString(TOKEN);
        Integer hostAudit = MmkvUtil.INSTANCE.decodeInt(HOSTAUDIT);
        if (hostAudit != null && hostAudit == 1) {
            imageOneTouchChat.setVisibility(View.VISIBLE);
        } else {
            imageOneTouchChat.setVisibility(View.GONE);
        }
        imageOneTouchChat.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                new XPopup.Builder(requireContext())
                        .hasShadowBg(false)
                        .asCustom(new OneTouchChatDialog(requireContext()))
                        .show();
            }

            @Override
            protected void onFastClick() {

            }
        });
        //设置选中 下划线样式的方法
        //tab_home.setSelectedTabIndicator();
        tosearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), SearchActivity.class);
                startActivity(intent);
            }
        });
        vp_home.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });


        fragmentlist.clear();

        fragmentlist.add(new TuijianFragment());
        fragmentlist.add(new TongchengFragment());
        fragmentlist.add(new OnLineFragment());
        fragmentlist.add(new NewFragment());
        fragmentlist.add(new FriendFollowFragment());

        vp_home.setAdapter(new FragmentStateAdapter(getChildFragmentManager(), getLifecycle()) {

            @Override
            public int getItemCount() {
                return fragmentlist.size();
            }

            @NonNull
            @Override
            public Fragment createFragment(int position) {
                return fragmentlist.get(position);
            }
        });
        vp_home.setOffscreenPageLimit(5);
        ViewPager2Delegate.Companion.install(vp_home, tab_home, null);
        LiveEventBus.get("GO_TO_VIDEO", String.class).observe(this, s -> {
            if (s.isEmpty()) return;
            getimPre(EXTRA, s, MmkvUtil.INSTANCE.decodeString(TOKEN));
        });
        LiveEventBus.get("SAY_HELLO", String.class).observe(this, s -> {
            if (s.isEmpty()) return;
            sayhello(MmkvUtil.INSTANCE.decodeString(TOKEN), EXTRA, Integer.parseInt(s));
        });
    }

    @Override
    protected void lazyLoad() {
        NetUtils2.getInstance().getApiService().getHomeUserInfo(token, EXTRA)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        LogUtils.i("解密后的数据为", decryptStr);
                        Gson gson = new Gson();
                        MineInfoBean bean = gson.fromJson(decryptStr, MineInfoBean.class);
                        if (bean != null) {
                            if (bean.getData() != null) {
                                if (bean.getData().getUser() != null) {
                                    MmkvUtil.INSTANCE.encode(USERID, bean.getData().getUser().getUserId());
                                    host = bean.getData().getUser().getHost();
                                    if (host == 1) {
                                        fragmentlist.add(new OperationsFragment());

                                        TextView textView = new TextView(getContext());
                                        textView.setGravity(Gravity.CENTER);
                                        textView.setText(requireContext().getString(R.string.mi_dongtai));
                                        tab_home.addView(textView);

                                        if (vp_home.getAdapter() != null) {
                                            vp_home.getAdapter().notifyItemChanged(fragmentlist.size());
                                        }
                                    }
                                }
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    private void getimPre(String extra, String toUserId, String token) {
        NetUtils.getInstance().getApiService().getimPre(extra, toUserId, token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        com.blankj.utilcode.util.LogUtils.i("decryptStr10", decryptStr);
                        Gson gson = new Gson();
                        OurinfoBean bean = gson.fromJson(decryptStr, OurinfoBean.class);
                        TestActivity.ourinfoBean = bean;
                        if (bean.getCode() == 0) {
                            //可以发起通话
                            int accId = com.luoxiang.lib_common.utils.MmkvUtil.INSTANCE.decodeInt(ACCID);
                            String id = UUID.randomUUID().toString().replace("-", "");
                            CallParam param = CallParam.createSingleCallParam(2, accId + "", toUserId + "", null, null, id);
                            CallKitUI.startSingleCall(getContext(), param);
                        } else {
                            ToastUtils.showShort(bean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void sayhello(String token, String extra, int userid) {
        getRequest();
        NetUtils2.getInstance().getApiService().sayHello(token, extra, userid)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        LogUtils.i("decryptStrdazhaohu", decryptStr);
                        Gson gson = new Gson();
                        GetMessageBean getMessageBean = gson.fromJson(decryptStr, GetMessageBean.class);
                        if (getMessageBean.getCode() == 0) {
                        } else {
                            ToastUtils.showShort(getMessageBean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
